package com.example.httpsocket.entity;

import com.google.gson.Gson;
import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/8/27 9:57
 */
/*
    http响应报文
 */
@Data
@Slf4j
public class MyResponse {
    private OutputStream outputStream;
    private String http = "HTTP/1.1";
    private int status;
    private String desc;
    private String header;
    private Date date;
    private HashMap<String, Object> body;
    private String responseHeader;
//    public String responseHeader = "HTTP/1.1 200\r\n" + "Content-Type:text/html\r\n"+"\r\n"+"{'header': " + header + ", 'username':'huang','pwd':'123456'}";

    public MyResponse(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    public void write(int status, String desc, String header, HashMap body){
        Gson gson = new Gson();
        String bodyJson = gson.toJson(body);
        responseHeader = http + " " + status + " " + desc + "\r\n" + header + "\r\n" + new Date() + "\r\n" + "\r\n" + bodyJson;
        try {
            outputStream.write(responseHeader.getBytes());
            log.info("http响应报文发送成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
